package com.cryptooj.project.controller;

import cn.hutool.core.io.FileUtil;
import com.cryptooj.project.common.BaseResponse;
import com.cryptooj.project.common.ErrorCode;
import com.cryptooj.project.common.ResultUtils;
import com.cryptooj.project.constant.FileConstant;
import com.cryptooj.project.exception.BusinessException;
import com.cryptooj.project.manager.CosManager;
import com.cryptooj.project.model.entity.User;
import com.cryptooj.project.model.enums.FileUploadBizEnum;
import com.cryptooj.project.service.UserService;
import com.cryptooj.project.model.dto.file.UploadFileRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {
    @Resource
    private UserService userService;

    @Resource
    private CosManager cosManager;

    /**
     *  文件上传
     * */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file")MultipartFile multipartFile,
                                           UploadFileRequest uploadFileRequest,
                                           HttpServletRequest request){
        String biz = uploadFileRequest.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if(fileUploadBizEnum == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        validFile(multipartFile, fileUploadBizEnum);
        User loginUser = userService.getLoginUser(request);
        // 文件上传至服务器后如何存储：按照业务、用户来划分文件夹
        String uuid = RandomStringUtils.randomAlphabetic(0);
        String filename = uuid+"-"+multipartFile.getOriginalFilename();
        String filepath = String.format("/%s/%s/%s",
                fileUploadBizEnum.getValue(),
                loginUser.getId(),
                filename);
        File file = null;
        try{
           // 上传文件
           file = File.createTempFile(filepath,null);
           multipartFile.transferTo(file);
           cosManager.putObject(filepath, file);
           // 返回供用户访问的可访问url
            return ResultUtils.success(FileConstant.COS_HOST+filepath);
        } catch (IOException e) {
            log.error("file upload error, filepath = {}", filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"文件上传失败！");
        } finally {
          if(file != null){
              // 删除临时文件
              boolean delete = file.delete();
              if(!delete){
                  log.error("file delete error, filepath = {}",filepath);
              }
          }
        }
    }

    /**
     *  校验文件
     * */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum){
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 1024*1024L;
        if(fileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)){
            if(fileSize > ONE_M){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小不能超过 1M ");
            }
            if(!Arrays.asList("jpeg","jpg","svg","png","webp").contains(fileSuffix)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件类型错误");
            }
        }
    }
}
